﻿/*
 * This code contained within HttpPost and HttpGet came 
 * from Dr. M Elkstein's blog, at 
 * http://rest.elkstein.org/2008/02/using-rest-in-c-sharp.html
 * 
 * No copywrite was stated on the page.
 * Crash (Joshua) Collison added the second overload of HttpPost, 
 * "public static string HttpPost(string url, string prebuiltParams)", and 
 * modified the first HttpPost to include the optional argument "string extras".
 */


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.IO;
using Newtonsoft.Json;
using System.Diagnostics;

namespace NetLib
{
    public static class RESTProcessor
    {
        #region Data and Properties
        #endregion //Data and Properties

        #region Contstructors

        //public RESTProcessor()
        //{

        //}

        #endregion //Contstructors

        #region Methods

        public static string HttpPost(string url, string[] paramNames, string[] paramValues, string extras = null)
        {
            //http://rest.elkstein.org/2008/02/using-rest-in-c-sharp.html
            string result;

            HttpWebRequest request = WebRequest.Create(new Uri(url)) as HttpWebRequest;

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            //build parameters string
            StringBuilder parameters = new StringBuilder();
            for (int i = 0; i < paramNames.Length; i++)
            {
                parameters.Append(paramNames[i]);
                parameters.Append("=");
                parameters.Append(HttpUtility.UrlEncode(paramValues[i]));
                parameters.Append("&");
            }

            if (extras != null)
            {
                parameters.Append((extras));
            }

            //convert parameter string to bytes
            byte[] formData = UTF8Encoding.UTF8.GetBytes(parameters.ToString());
            request.ContentLength = formData.Length;

            //send the request
            using (Stream post = request.GetRequestStream())
            {
                post.Write(formData, 0, formData.Length);
            }

            //Grab the responce
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                result = reader.ReadToEnd();
            }


            return result;
        }

        public static string HttpPost(string url, string prebuiltParams)
        {

            string result;

            HttpWebRequest request = WebRequest.Create(new Uri(url)) as HttpWebRequest;

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            //build parameters string
            string parameters = prebuiltParams;// HttpUtility.UrlEncode(prebuiltParams);

            //convert parameter string to bytes
            byte[] formData = UTF8Encoding.UTF8.GetBytes(parameters);
            request.ContentLength = formData.Length;

            //send the request
            using (Stream post = request.GetRequestStream())
            {
                post.Write(formData, 0, formData.Length);
            }
            //Grab the response
            try
            {
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                throw ex;
            }
            return result;
        }

        public static string HttpPost(string url, List<string> header, bool useHeaderAuth)
        {
            string result;

            HttpWebRequest request = WebRequest.Create(new Uri(url)) as HttpWebRequest;

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            StringBuilder authorizationHeaderParams = new StringBuilder("OAuth ");


            //header.Sort();

            foreach (var item in header)
            {
                var param = item.Split('=');
                authorizationHeaderParams.Append(param[0]);
                authorizationHeaderParams.Append("=\"");
                authorizationHeaderParams.Append(Uri.EscapeDataString(param[1]));
                if (item != header.Last())
                {
                    authorizationHeaderParams.Append("\",");
                }
                else
                {
                    authorizationHeaderParams.Append("\"");
                }
            }




            request.Headers.Add("Authorization", authorizationHeaderParams.ToString());

            //convert parameter string to bytes
            byte[] formData = UTF8Encoding.UTF8.GetBytes(string.Empty);
            request.ContentLength = formData.Length;


            //send the request
            using (Stream post = request.GetRequestStream())
            {
                post.Write(formData, 0, formData.Length);
            }
            //Grab the response
            try
            {
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                throw ex;
            }


            return result;
        }



        public static string HttpGet(string url)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse resp = null;
            string result = null;
            try
            {
                resp = (HttpWebResponse)req.GetResponse();
                StreamReader reader =
                    new StreamReader(resp.GetResponseStream());
                result = reader.ReadToEnd();
            }
            catch (WebException ex)
            {
                //var response = (HttpWebResponse)ex.Response;
                Debug.WriteLine("### ERROR: " + ex.ToString() + " " + ex.Response);
            }
            finally
            {
                if (resp != null)
                {
                    resp.Close();
                }
            }



            return result;
        }


        public static string HttpGet(string url, List<string> header)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse resp = null;
            string result = null;

            StringBuilder authorizationHeaderParams = new StringBuilder(string.Format("OAuth realm=\"{0}\",", 
                Uri.EscapeDataString("api.fitbit.com")));


            //header.Sort();

            foreach (var item in header)
            {
                var param = item.Split('=');
                authorizationHeaderParams.Append(param[0]);
                authorizationHeaderParams.Append("=\"");
                
                if (item != header.Last())
                {
                    
                    authorizationHeaderParams.Append(Uri.EscapeDataString(param[1]));
                    authorizationHeaderParams.Append("\", ");
                }
                else
                {
                    authorizationHeaderParams.Append(param[1]);
                    authorizationHeaderParams.Append("=\"");
                }
            }




            req.Headers.Add("Authorization", authorizationHeaderParams.ToString());





            try
            {
                resp = (HttpWebResponse)req.GetResponse();
                StreamReader reader =
                    new StreamReader(resp.GetResponseStream());
                result = reader.ReadToEnd();
            }
            catch (WebException ex)
            {
                //var response = (HttpWebResponse)ex.Response;
                Debug.WriteLine("### ERROR: " + ex.ToString() + " " + ex.Response);
            }
            finally
            {
                if (resp != null)
                {
                    resp.Close();
                }
            }



            return result;
        }








        #endregion //Methods
    }
}

